import axios from "axios";
import { getToken, removeToken } from "./cookie";
import router from "@/router";

//不同的功能通过axios请求的是不同的接口地址
const service = axios.create({
  baseURL: "/dev-api", //请求接口前缀
  timeout: 5000, //请求超时时间
});

//配置请求连接器，用于在请求发送前做一些重复的事情
service.interceptors.request.use(
  (config) => {
    if(getToken()){
      config.headers["Authorization"] = "Bearer "+getToken()
    }
    return config;
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
);


//配置响应拦截器  用于处理接口返回的结果提前判断
service.interceptors.response.use(
  (res) => {  //res:后端响应的数据
    // 未设置状态码则默认成功状态
    const code = res.data.code;
    const msg = res.data.msg;
    if(code === 3001){
      ElMessage.error(msg)
      removeToken()
      router.push('/login')
      return Promise.reject(new Error(msg))
    }
    if (code !== 1000) {
      ElMessage.error(msg);
      return Promise.reject(new Error(msg));
    } else {
      return Promise.resolve(res.data);
    }

  },
  (error) => {
    return Promise.reject(error);
  }
);



export default service; //将service实例暴露出去
